<?php

namespace yan\backendclient\modules\role\models;

use Yii;

/**
 * This is the model class for table "{{%backend_role}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $type
 * @property integer $created_at
 * @property integer $updated_at
 */
class Role extends \yii\db\ActiveRecord
{

    public $permissions;

    public $roles;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%backend_role}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['created_at', 'updated_at'], 'integer'],
            [['name'], 'string', 'max' => 255],
            [['type'], 'string', 'max' => 24],
            [['roles', 'permissions'], 'default', 'on' => 'role'],
        ];
    }

    // public function scenarios()
    // {
    //     return [
    //         'role' => ['roles', 'permissions']
    //     ];
    // }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('debug', 'ID'),
            'name' => Yii::t('debug', 'Name'),
            'type' => Yii::t('debug', 'Type'),
            'created_at' => Yii::t('debug', 'Created At'),
            'updated_at' => Yii::t('debug', 'Updated At'),
            "permissions" => Yii::t('debug', 'Permissions'),
            "roles" => Yii::t('debug', 'Role'),
        ];
    }

    // 行為
    public function behaviors()
    {

        $data = \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ]
        ]);
        return $data;
    }

    // 关联rule表
    public function getRules(){
        return $this->hasMany(RoleRule::className(), ['role_id'=>'id']);
    }

    public function getPermissionsByGroup($type='index'){
        $model = new BackendRoleItem;
        return $model->getPermissionsByGroup($type);
    }

    public function fillModel(){
        $temp = RoleRule::findAll(['role_id'=>$this->id]);
        $permissions = [];
        foreach ($temp as $permission){
            $permissions[$permission->control] = $permission->control;
        }
        $this->permissions = $permissions;
    }

    public function updateRole()
    {
        $oldModel = clone $this;
        $oldModel->fillModel();

        $oldPermissions = array_keys( $oldModel->permissions );

        if( $this->permissions === null ) $this->permissions = [];
        $this->permissions = array_flip($this->permissions);
        if (isset($this->permissions[0])) unset($this->permissions[0]);
        $this->permissions = array_flip($this->permissions);

        $needAdds = array_diff($this->permissions, $oldPermissions);

        foreach ($needAdds as $key => $permission){
            $role = new RoleRule;
            $role->role_id = $this->id;
            $role->control = $permission;
            if(!empty($oldModel->permissions[$key])){
                $role->alias_name = $oldModel->permissions[$key]->description;
            }
            $role->save();

        }

        $needRemoves = array_diff($oldPermissions, $this->permissions);
        foreach ($needRemoves as $permission){
            $role = RoleRule::findOne(['role_id'=>$this->id,
                    'control' => $permission
                    ]);
            if($role){
                $role->delete();
            }
        }

        return true;

    }
}
